import os
from datetime import datetime
import exifread
from PIL import Image
from location_service import getLatOrLng
import random

class ImageProcessor:
    """处理单个图片的类，负责提取和显示图片的EXIF信息"""
    
    def __init__(self, image_path):
        self.image_path = image_path
        self.has_exif = False  # 添加标记是否有EXIF信息
        
    def process(self):
        """处理图片，提取并显示信息"""
        try:
            # 首先重命名文件
            self.rename_file()
            
            # 读取EXIF信息
            with open(self.image_path, 'rb') as f:
                tags = exifread.process_file(f)
            print(f'\n处理图片: {self.image_path}')
            
            # 设置EXIF标记
            self.has_exif = bool(tags and 'EXIF DateTimeOriginal' in tags)
            
            if not tags:
                self._show_basic_info()
                return
                
            self._show_exif_info(tags)
            
        except Exception as e:
            print(f'处理图片时出错 {self.image_path}: {str(e)}')
    
    def has_exif_info(self):
        """返回是否包含EXIF信息"""
        return self.has_exif
    
    def rename_file(self):
        """根据拍摄日期或修改日期重命名文件"""
        try:
            # 获取文件所在目录和扩展名
            directory = os.path.dirname(self.image_path)
            ext = os.path.splitext(self.image_path)[1].lower()
            
            # 对于PNG和BMP文件，直接使用文件修改时间
            if ext in ('.png', '.bmp'):
                mtime = os.path.getmtime(self.image_path)
                date_str = datetime.fromtimestamp(mtime).strftime('%Y%m%d_%H%M%S')
            else:
                # 尝试从EXIF获取拍摄日期
                date_str = None
                with open(self.image_path, 'rb') as f:
                    tags = exifread.process_file(f)
                    if tags and 'EXIF DateTimeOriginal' in tags:
                        date_time = datetime.strptime(str(tags['EXIF DateTimeOriginal']), '%Y:%m:%d %H:%M:%S')
                        date_str = date_time.strftime('%Y%m%d_%H%M%S')
                
                # 如果没有EXIF日期，使用文件修改时间
                if not date_str:
                    mtime = os.path.getmtime(self.image_path)
                    date_str = datetime.fromtimestamp(mtime).strftime('%Y%m%d_%H%M%S')
            
            # 生成新文件名
            counter = 0
            while True:
                suffix = f'_{counter}' if counter > 0 else ''
                new_name = f'IMG_{date_str}{suffix}{ext}'
                new_path = os.path.join(directory, new_name)
                
                if not os.path.exists(new_path) or new_path == self.image_path:
                    break
                counter += 1
            
            # 如果文件名不同，则重命名
            if new_path != self.image_path:
                os.rename(self.image_path, new_path)
                print(f'重命名文件: {os.path.basename(self.image_path)} -> {new_name}')
                self.image_path = new_path
                
        except Exception as e:
            print(f'重命名文件时出错 {self.image_path}: {str(e)}')
            
    def _show_basic_info(self):
        """显示基本文件信息"""
        print('未找到EXIF信息，显示基本文件信息：')
        # 获取文件时间信息
        creation_time = os.path.getctime(self.image_path)
        modified_time = os.path.getmtime(self.image_path)
        
        creation_date = datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d %H:%M:%S')
        modified_date = datetime.fromtimestamp(modified_time).strftime('%Y-%m-%d %H:%M:%S')
        
        print('创建时间：', creation_date)
        print('修改时间：', modified_date)
        
        # 获取图片分辨率
        with Image.open(self.image_path) as img:
            width, height = img.size
            print(f'照片尺寸：{width} x {height}')
            
    def _show_exif_info(self, tags):
        """显示EXIF信息"""
        print('拍摄时间：', tags.get('EXIF DateTimeOriginal', 'Unknown'))
        print('照相机制造商：', tags.get('Image Make', 'Unknown'))
        print('照相机型号：', tags.get('Image Model', 'Unknown'))
        print('照片尺寸：', tags.get('EXIF ExifImageWidth', 'Unknown'), 
              tags.get('EXIF ExifImageLength', 'Unknown'))
        
        lat = getLatOrLng(tags, 'GPS GPSLatitudeRef', 'GPS GPSLatitude')
        lng = getLatOrLng(tags, 'GPS GPSLongitudeRef', 'GPS GPSLongitude')
        if lat and lng:
            print('纬度:{} 经度：{}'.format(lat, lng)) 